﻿using AutoMapper;
using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.Produce.Supplier;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Set.API.Application.Commands.Supplier
{
    public class ContactPersonsUpdateHandler : IRequestHandler<ContactPersonsUpdateCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        /// <summary>
        /// 联系人信息
        /// </summary>
        private readonly IBaseRepository<ContactPersons> contactPersonsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ContactPersonsUpdateHandler> logger;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contactPersonsRepository"></param>
        /// <param name="mapper"></param>
        public ContactPersonsUpdateHandler(IBaseRepository<ContactPersons> contactPersonsRepository, IMapper mapper, ILogger<ContactPersonsUpdateHandler> logger)
        {
            this.contactPersonsRepository = contactPersonsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<Result> Handle(ContactPersonsUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Update };

            try
            {
                logger.LogInformation("联系人修改");
                var AddData = mapper.Map<ContactPersons>(request);
                string sql = "UPDATE ContactPersons SET ContactPersonsName=@ContactPersonsName ,ContactPersonsTell=@ContactPersonsTell ,Position=@Position ,ContactPersonStatus =1 WHERE ContactPersonsId =@ContactPersonsId ";
                var AddNum = contactPersonsRepository.Update(sql, new
                {
                    ContactPersonsId = AddData.ContactPersonsId,
                    ContactPersonsName = AddData.ContactPersonsName,
                    ContactPersonsTell = AddData.ContactPersonsTell,
                    Position = AddData.Position,
                    ContactPersonStatus = AddData.ContactPersonStatus,
                });
                if (AddNum > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    return result;
                    
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                logger.LogError("联系人修改失败" + ex.Message);

                throw;
            }
        }
    }
}
